package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.AnnualPara;
import com.cfets.annualAssessment.entity.TableContainer;
import com.cfets.annualAssessment.service.AnnualInformService;
import com.cfets.annualAssessment.service.AnnualParaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by ShenYiChou on 2017/1/23.
 */
@Controller
@RequestMapping("/admin/annualpara")
public class AnnualParaController {
    @Autowired
    private AnnualInformService annualInformService;
    @Autowired
    private AnnualParaService annualParaService;

    @RequestMapping("/index")
    public String index(Model model){
        return "annualPara";
    }
    @RequestMapping("/statistics")
    public String statisticsindex(Model model){
        return "statistics";
    }
    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> annualInformList(AnnualPara annualPara){
        List<AnnualPara> annualInformList = annualParaService.getAnnualParaPage(annualPara);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(annualInformList);
        tableContainer.setiTotalDisplayRecords(annualPara.getTotalCount());
        tableContainer.setiTotalRecords(annualPara.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }
    @RequestMapping(value = "/certStat",method = RequestMethod.GET)
    public ResponseEntity<?> certStat(){
        int[] certStat = annualParaService.conCertStat();
        return new ResponseEntity<>(certStat, HttpStatus.OK);
    }
    @PostMapping
    public ResponseEntity<?> createOrUpdate(@Valid AnnualPara annualPara, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        boolean flag = false;
        if (!annualParaService.annualParaIsValid(annualPara)){
            return new ResponseEntity<>(-1, HttpStatus.OK);
        }
        if(annualPara.getId()!=null && annualPara.getId()!=0){
            flag = this.annualParaService.updateAnnualPara(annualPara);
        }else {
            flag = this.annualParaService.newAnnualPara(annualPara);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAnnualPara(@PathVariable("id") int id){
        boolean flag = this.annualParaService.deleteAnnualParaById(id);
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
}
